package service

import (
	"context"
	context2 "elflog/common/context"
	"elflog/common/errs"
	"elflog/common/utils/str_util"
	"elflog/module/module-log/model"
)

func (a *ModuleLogService) StartSaveWorker(ctx context.Context) {
	a.startSaveLogOnce.Do(func() {
		a.waitSaveLog.Add(1)
		go func() {
			defer a.waitSaveLog.Done()
			for {
				log, isOk := <-a.saveLogChannel
				if !isOk {
					break
				} else {
					func() {
						defer func() {
							if err := recover(); err != nil {
								a.log.Errorf("save log panic %v %v", err, str_util.ToJson(log))
							}
						}()
						err := a.CreateLog(log.Ctx, log.CreateLogModel)
						a.log.Errorf("save log error %v %v", err, str_util.ToJson(log))
					}()
				}
			}
		}()
	})
}

func (a *ModuleLogService) StopSaveWorker(ctx context.Context) {
	a.stopSaveLogOnce.Do(func() {
		close(a.saveLogChannel)
		a.waitSaveLog.Wait()
		a.log.Warn("save log channel closed")
	})
}

func (a *ModuleLogService) PushLog(ctx context.Context, log *model.CreateLogModel) (err error) {
	defer func() {
		if err2 := recover(); err2 != nil {
			err = errs.NewInternal().WithMsgf("%v", err2)
		}
	}()
	var nCtx = context2.MustGetContext(ctx).Clone()
	nCtx.Tx = nil
	var msg = &model.CreateLogModelForChannel{
		CreateLogModel: log,
		Ctx:            nCtx,
	}
	a.saveLogChannel <- msg
	return err
}
